import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {StorageService} from './storage.service';
import {PageButton} from '../model/page-button.model';
import {AppContextService} from './app-context.service';
import {HttpParams} from '@angular/common/http';
import {HttpClientService} from './http-client.service';
import {Clone, HandleDictionaryObj} from '../utils';
import {IPDialog} from '../model/share.model';

@Injectable()
export class EntityService {
  test = 'EntityService';
  _params: any;
  pageData: any;   // 页面配置内容
  dictionaries: any;  // 页面字典
  dialog: any;
  dialogData: any;
  oldListData: any[] = [];   // 原来的列表数据（用于表编辑时使用）
  constructor(
    private bHttp: HttpClientService,
    private bApp: AppContextService,
    private bStorage: StorageService,
  ) { }

  get urlDictionary(){
    return `/api/${enumController[enumController.comDictionary]}/${enumAction[enumAction.GetTableDicList]}`;
  }
  /**
   * 配置信息的控制器string
   * @returns {string}
   */
  get urlController(){
    return `/api/${ this.pageData.controller }`;
  }

  httpUrl() {
    return {
      controller: `${this.urlController}` ,
      page: `${this.urlController}/${ enumAction[enumAction.PageList]}` ,
      delete: `${this.urlController}` ,
    };
  }
  /**
   * 页面标题
   */
  get title(){
    return this.pageData.title;
  }

  /**
   * 页面中的按钮信息
   * @returns {PageButton}
   */
  get buttons(){
    let listBtnData = [];
    if (this.bStorage.menuCurr) {
      const currModule = this.bStorage.menuCurr;
      if (currModule && currModule['functions'] && currModule['functions'].length > 0) {
        const buttonData = currModule['functions'];
        // listBtnData=buttonData.filter(m=>m.layout.indexOf('list')>=0);
        listBtnData = buttonData;
      }
    }
    const buttons = new PageButton();
    buttons.listTopButtons = listBtnData.filter(m => m.layout === 'top');
    buttons.listRowButtons = listBtnData.filter(m => m.layout === 'row');
    buttons.hasRowButtons = buttons.listRowButtons.length > 0 ? true : false;
    return buttons;
  }

  /**
   * 页面配置信息的列表信息
   * @returns {{}}
   */
  get list(){
    if (this.pageData['list']) {
      return this.pageData.list;
    } else {
      return {};
    }
  }

  /**
   * 页面配置信息的列表信息中的分页信息
   * @returns {any | Pager}
   */
  get pager(){
    return this.list.pager;
  }

  /**
   * 页面中的查询参数
   * @returns {any}
   */
  get params(){
    this._params = {};
    if (this.pageData['search'] && this.pageData.search['cols']) {
      let self = this;
      this.pageData.search.cols.forEach(item => {
        if (item['defaultValue']) {
          self._params[item.field] = item['defaultValue'];
        } else {
          self._params[item.field] = null;
        }
      });
    }
    return this._params;
  }

  /**
   * 分页信息（页码，行数）
   * @returns {{pagesize: number; pageindex: number}}
   */
  get pageParams(){
    return {
      pagesize: this.pager.pageSize,
      pageindex: this.pager.pageIndex
    };
  }

  /**
   * 分页信息string（页码，行数）
   * @returns {string}
   */
  get pageUrlParams(){
    let queryString = '';
    Object.keys(this.pageParams).forEach(field => {
      if ( this.pageParams[field] ) {
        queryString += queryString.length > 0
          ? `&${field}=${this.pageParams[field]}`
          : `${field}=${this.pageParams[field]}`;
      }
    });
    return queryString;
  }

  /**
   * 当前页面的请求地址
   */

  /**
   * 页面按钮点击事件
   * @param btn : 按钮信息
   * @param item : 触发事件时传的数据
   */
  btnClick(btn, item?) {
    btn = this.bApp.btnCodeToBtnObject(btn);
    switch (btn.functionCode) {
      case enumBtnCode[enumBtnCode.add]:
        this.showAddDialog(item);
        break;
      case enumBtnCode[enumBtnCode.edit]:
        this.showEditDialog(item);
        break;
      case enumBtnCode[enumBtnCode.delete]:
        this.delete(item);
        break;
      case enumBtnCode[enumBtnCode.search]:
        this.search(item);
        break;
      case enumBtnCode[enumBtnCode.refresh]:
        this.loadPage();
        break;
        case enumBtnCode[enumBtnCode.tableSave]:
          console.log(this.oldListData[0]);
          console.log(this.list.data[0]);
          break;
    }
  }
  /**
   * 分页加载列表
   * @param {HttpParams} params: 查询参数
   */
  loadPage(params?: HttpParams) {
    if (!params) {
      params = new HttpParams({fromObject: this.pageParams});
    }
    if (this.httpUrl()['page']) {
      const url = this.httpUrl()['page'];
      this.bHttp.get(url, params )
        .subscribe(res => {
          if (res.success) {
            this.pageData.list.data = res.data.data;
            res.data.data.forEach(item => {
              this.oldListData.push(item);
            });
            // this.oldListData = res.data.data;
            // this.pageData.list.loading = false;
            this.pageData.list.pager.totalCount = res.data.totalCount;
            console.log(this.pageData.list.data);
          }
        });
    }
  }

  /**
   * 加载字典
   * @param {string} _url
   * @param {string} _tableName
   */
  loadDictionary(_url?: string, _tableName?: string) {
    const url = _url ? _url : this.urlDictionary;
    const tableName = _tableName ? _tableName : this.pageData.controller;
    const params = new HttpParams().set('tablename', tableName);
    this.bHttp.get(url, params)
      .subscribe(res => {
        if (res.success) {
          this.dictionaries = HandleDictionaryObj(res.data);
          console.log(this.dictionaries);
        }
      });
  }

  load() {}

  /**
   * 显示新增窗口
   * @param item
   */
  showAddDialog(item?: any) {
    if (this.pageData.dialog && this.pageData.dialog.add) {
      const dialogConfig = this.pageData.dialog.add;
      this.bApp.showDialog({
        header: dialogConfig ? dialogConfig.header : '新增',
        width: dialogConfig ? dialogConfig.width : '600',
        top: dialogConfig ? dialogConfig.top : '180',
        yes: (model) => {
          this.save(model);
        }}, this, this.dialog.add, item);
    }
  }

  /**
   * 显示编辑窗口
   * @param item
   */
  showEditDialog(item?: any) {
    const newItem = Clone(item);
    if (this.pageData.dialog && this.pageData.dialog.add) {
      const dialogConfig = this.pageData.dialog.add;
      this.bApp.showDialog({
        header: dialogConfig ? dialogConfig.header : '编辑',
        width: dialogConfig ? dialogConfig.width : '600',
        top: dialogConfig ? dialogConfig.top : '180',
        yes: (model) => {
          this.save(model);
        }}, this, this.dialog.add, newItem);
    }
  }

  /**
   * 实体保存数据函数
   * @param data
   */
  save(model?: any) {
    this.bHttp.post(this.urlController, model)
      .subscribe(res => {
        if ( res.success) {
          this.bApp.msg.success('操作成功！');
          this.loadPage();
        }
      });
  }

  delete(item) {
    this.bApp.confirm({
      yes: () => {
        // const params = new HttpParams().set('id', item.id);
        this.bHttp.delete(`${this.httpUrl().delete}/${item.id}`)
          .subscribe(res => {
            if (res.success) {
              this.bApp.msg.success('删除成功！');
              this.loadPage();
            }
          });
      }
    });
  }
  search(params) {
    this.loadPage(params);
  }
  clear() {}
}

export enum enumBtnCode {
  add,
  edit,
  delete,
  search,
  refresh,
  clear,
  tableSave
}
export enum enumAction {
  List,
  PageList,
  MapList,
  Post,
  Detail,
  Import,
  Delete,
  DeleteItem,
  Export,
  DownloadExportModel,
  GetCode,
  GetTableDicList,
  SetButton,
  SetPermission,
  GetSubItem
}
export enum enumController {
  busCourtyard,
  busCuring,
  busGreenbelt,
  busLandscape,
  busMap,
  busOldTree,
  busPlantInfo,
  busPlantType,
  busReform,
  busReformLandscape,
  busReformOldTree,
  busReformPlantInfo,
  ContrastAnalysis,
  DataCountCensus,
  GreenQuotaCensus,
  HistoryAnalysis,
  HistoryDataSelect,
  Home,
  PlantTypeCensus,
  Tree,
  Token,
  comDictionary,
  sysFunction,
  sysModule,
  sysUser,
  sysUnit,
  sysRole,
}
export enum enumDialog {

}

